package com.demomaster.quickaccessibility.model;

import android.accessibilityservice.GestureDescription;
import android.graphics.Path;
import android.os.Build;

import com.demomaster.quickaccessibility.service.QuickAccessibilityHelper;
import com.demomaster.quickaccessibility.service.QuickAccessibilityService;

import java.util.ArrayList;
import java.util.List;

/**
 * 手势构建
 */
public class GestureBuilder {
    class GestureAction {
        int startTime;
        int duration;
        Path path;
        List<Path> pathList = new ArrayList<>();
    }

    List<GestureAction> gestureActionList = new ArrayList<>();

    public GestureBuilder move(int fromX, int fromY, int toX, int toY, int startTime, int duration) {
        Path path = new Path();
        path.moveTo(fromX, fromY);
        path.lineTo(toX, toY);
        GestureAction gestureAction = new GestureAction();
        gestureAction.duration = duration;
        gestureAction.startTime = startTime;
        gestureAction.path = path;
        gestureAction.pathList.add(path);
        gestureActionList.add(gestureAction);
        return this;
    }

    public void build() {
        GestureDescription.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder = new GestureDescription.Builder();
            try {
                for (GestureAction gestureAction : gestureActionList) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        GestureDescription.StrokeDescription description1 = new GestureDescription.StrokeDescription(gestureAction.path, gestureAction.startTime, gestureAction.duration, true);
                        builder.addStroke(description1);
                    } else {
                        builder.addStroke(new GestureDescription.StrokeDescription(gestureAction.path, gestureAction.startTime, gestureAction.duration));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            QuickAccessibilityService.instance.dispatchGesture(builder.build(), null, null);
        }
    }
}